<template>
	<view class="chat-room container">
		<uni-nav-bar shadow fixed left-icon="left" :right-icon="convInfo.type == 2 && 'more-filled' || ''" @clickRight="actionHandle"
			@clickLeft="routeBack" :title="`${convInfo.name}[${convInfo.id}]`">
		</uni-nav-bar>
		<view class="chat-warp" @click="isOpenBar = false">
			<view class="chat-content">
				<view v-for="item in msgs" class="chat-item" :class="item.direction == 0 ? 'self' : ''"
					:key="item.messageID">
					<view class="chat-msg">
						<image v-if="getChatAvatar(item.senderUserID)" class="avatar"
							:src="getChatAvatar(item.senderUserID)" mode="aspectFill" />
						<uni-icons v-else type="contact" class="avatar" size="32" />
						<view class="msg-content">
							<view class="name-box">{{ item.senderUserID }}</view>
							<view class="msg-box" v-if="item.thumbnailDownloadUrl">
								<image mode="widthFix" style="width: 240px;" :src="item.thumbnailDownloadUrl"></image>
							</view>
							<view class="msg-box" v-else-if="item.videoFirstFrameDownloadUrl">
								<video style="width: 240px;" :src="item.fileDownloadUrl"
									:poster="item.videoFirstFrameDownloadUrl" />
							</view>
							<view class="msg-box" v-html="transMsg(item)" v-else></view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="send-input">
			<uni-icons type="plus" size="24" @click="isOpenBar = true"></uni-icons>
			<uni-search-bar style="flex: 1" placeholder=" " clearButton="none" cancelButton="always" cancelText="Send"
				@cancel="sendMessage">
				<uni-icons slot="searchIcon" color="#999999" size="18" type="chat" />
			</uni-search-bar>
		</view>
		<uni-grid class="bottom-btn" :column="5" @change="clickBBtn" :showBorder="false" v-if="isOpenBar">
			<uni-grid-item :showBorder="false">
				<view class="grid-item-box">
					<uni-icons :type="isByte ? 'paperplane-filled' : 'paperplane'" @click="isByte = !isByte" :size="30"
						color="#777" />
					<view class="text"></view>
				</view>
			</uni-grid-item>
			<!--  #ifdef  H5 || MP-WEIXIN -->
			<uni-grid-item :showBorder="false" v-for="item in featureBar" :key="item.name" :index="item.type">
				<view class="grid-item-box">
					<uni-icons :type="item.name" :size="30" color="#777" />
					<view class="text"></view>
				</view>
			</uni-grid-item>
			<!--  #endif -->
		</uni-grid>
	</view>
</template>

<script>
	import {
		zim
	} from '../../store';
	export default {
		data() {
			return {
				convInfo: {},
				users: [],
				isByte: false,
				isOpenBar: false,
				featureBar: [{
						name: 'image',
						type: 11,
					},
					{
						name: 'videocam',
						type: 14,
					},
					{
						name: 'headphones',
						type: 13,
					},
					{
						name: 'folder-add',
						type: 12,
					},
				]
			};
		},
		// id=3333&type=0&name=3333
		onLoad(option) {
			this.convInfo = {
				...option,
				type: +option.type,
			};
			uni.setNavigationBarTitle({
				title: option.name+''
			});
			this.initEvent();
		},
		onShow() {
			this.queryHistoryMessage(this.convInfo);
			if (this.convInfo.type == 0) {
				wx.$store.setUserMap([wx.$store.state.user.baseInfo.userID, this.convInfo.id]);
			}
			if (this.convInfo.type == 2) {
				wx.$store.queryGroupMemberList(this.convInfo.id);
			}
		},
		computed: {
			msgs: function() {
				return wx.$store.state.chatMap[this.convInfo.id];
			},
		},
		watch: {
			isByte: function(newVal) {
				let title = 'Close signaling message';
				if (newVal) {
					title = 'Open signaling message';
				}
				uni.showToast({
					title,
					duration: 3000,
				});
			},
		},
		methods: {
			getChatAvatar(userID) {
				if (this.convInfo.type == 0) {
					return wx.$store.userMap[userID]?.userAvatarUrl;
				}
				if (this.convInfo.type == 2) {
					return wx.$store.userMap[userID]?.memberAvatarUrl;
				}
			},
			viewUser(id){
				this.$pv.msg(id);
			},
			initEvent() {
				wx.$store.$on('scroll2bottom', () => {
					this.scroll2bottom();
				});
				zim.on('roomStateChanged', (zim, data) => {
					const {
						state,
						event,
						extendedData,
						roomID
					} = data;
					console.log('===roomStateChanged===', state, event, extendedData, roomID);
					const stateTips = ['Disconnect', 'connecting', 'connected'];
					uni.showToast({
						title: stateTips[state],
						duration: 3000,
					});
					if (state == 0 && roomID == this.convInfo.id && this.convInfo.type == 1) {
						// this.routeBack();
					}
				});
				zim.on('roomMemberJoined', (zim, data) => {
					const {
						memberList,
						roomID
					} = data;
					console.log('===roomMemberJoined===', memberList, roomID);
					if (roomID !== this.convInfo.id) return;
					memberList.forEach((user) => {
						const userID = user.userID;
						const index = this.users.findIndex((item) => userID === item.userID);
						if (index == -1) {
							this.users.push(user);
						}
					});
					this.queryRoomOnlineMemberCount();
				});
				zim.on('roomMemberLeft', (zim, data) => {
					const {
						memberList,
						roomID
					} = data;
					console.log('===roomMemberLeft===', memberList, roomID);
					if (roomID !== this.convInfo.id) return;
					memberList.forEach((user) => {
						const userID = user.userID;
						const index = this.users.findIndex((item) => userID === item.userID);
						if (index == -1) {
							this.users.splice(index, 1);
						}
					});
					this.queryRoomOnlineMemberCount();
				});
				
				
			},

			queryHistoryMessage(message) {
				wx.$store
					.queryHistoryMessage(this.convInfo.id, +this.convInfo.type, {
						count: 1000,
						reverse: true,
					})
					.then(() => {
						this.scroll2bottom();
					});
			},

			queryRoomOnlineMemberCount() {
				wx.$store.queryRoomOnlineMemberCount(this.convInfo.id).then((res) => {
					this.title = `${this.convInfo.name}(${res.count})`;
				});
			},

			sendMessage(e) {
				const {
					type,
					id
				} = this.convInfo;
				const textMsg = e.value;
				wx.$store.sendChatMessage(type, textMsg, id, this.isByte).then((res) => {
					this.scroll2bottom();
				});
			},

			scroll2bottom() {
				const dom = document.body.getElementsByClassName('chat-warp')[0];
				dom && dom.scrollTo(0, 1000000);
			},

			actionHandle() {
				if (this.convInfo.type == 1) {
					this.routeToRoomMembers();
					return;
				}

				if (this.convInfo.type == 2) {
					this.routeToGroupInfo();
					return;
				}
			},

			routeBack() {
				if (this.convInfo.type == 1) {
					wx.$store.leaveRoom(this.convInfo.id);
				}
				if (this.msgs.length && this.convInfo.type !== 1) {
					wx.$store.clearConversationUnreadMessageCount(this.convInfo.id, +this.convInfo.type);
				}
				uni.switchTab({
					url: '../home/home',
				});
			},

			routeToRoomMembers() {
				uni.navigateTo({
					url: '../chat/memberList?roomID=' + this.convInfo.id,
				});
			},

			routeToGroupInfo() {
				const paramsString =
					'?' +
					Object.keys(this.convInfo)
					.map((key) => `${key}=${this.convInfo[key]}`)
					.join('&');
				uni.navigateTo({
					url: '../group/info' + paramsString,
				});
			},

			clickBBtn(e) {
				console.log(e);
				const type = e.detail.index;
				if (type < 10) return;
				const that = this;
				const params = {
					type,
				};

				if (type == 13) params.audioDuration = 5;
				if (type == 14) params.videoDuration = 5;
				// #ifdef H5
				let input = document.createElement('input');
				input.type = 'file';
				input.onchange = function() {
					console.log('this.files=', this.files);
					const file = this.files[0];
					params.fileLocalPath = file;
					wx.$store.sendMediaMessage({
							...params
						},
						that.convInfo.id,
						that.convInfo.type, {},
						(message, currentSize, totalSize) => {
							console.warn('file process', {
								message,
								currentSize,
								totalSize
							});
						},
					)
					that.isOpenBar = false;
					input = null;
				}
				input.click();
				// #endif
				// #ifdef MP-WEIXIN
				wx.chooseMessageFile({
					count: 1,
					success(res) {
						console.warn('chooseMessageFile', res);
						const file = res.tempFiles[0].path;
						wx.$store.sendMediaMessage({
								fileLocalPath: res.tempFiles[0].path,
								fileName: res.tempFiles[0].name,
								fileSize: res.tempFiles[0].size,
								type,
							},
							that.convInfo.id,
							that.convInfo.type, {},
							(message, currentSize, totalSize) => {
								console.warn('file process', {
									message,
									currentSize,
									totalSize
								});
							},
						)
						that.isOpenBar = false;
					}
				})
				// #endif
			},

			transMsg(item) {
				const msg = item.message;
				const isURLImg = (value) => /\w.(png|jpg|jpeg|svg|webp|gif|bmp)$/i.test(value);
				if (msg) {
					if (isURLImg(msg)) {
						return `<text>${msg}</text>` + `<image src=${msg} width="120" />`;
					}
				}
				if (item.fileName) {
					return `<a href="${item.fileDownloadUrl}">${item.fileName}</a>`;
				}
				return msg;
			}
		},
	};
</script>

<style lang="scss">
	.chat-room {
		height: 100vh;
		position: relative;
		display: flex;
		flex-direction: column;

		.chat-warp {
			flex: 1;
			position: relative;
			overflow-y: auto;

			.chat-content {
				box-sizing: border-box;
				width: 100%;
				position: absolute;
				left: 0;
				top: 0;
				padding: 16px 12px;

				.chat-item {
					&+.chat-item {
						margin-top: 24px;
					}

					.chat-time {
						margin: 16px 0;
						color: #8b8d94;
						text-align: center;
					}

					.chat-msg {
						display: flex;

						.avatar {
							width: 32px;
							height: 32px;
							-webkit-text-fill-color: #2979ff;
						}

						.msg-content {
							flex: 1;
							padding: 0 42px 0 12px;

							.name-box {
								padding: 0 0 0 2px;
								margin-top: -12px;
								font-size: 8px;
								color: #7a787b;
							}

							.msg-box {
								float: left;
								position: relative;
								padding: 6px 12px;
								max-width: 100%;
								word-break: break-word;
								background-color: #fff;
								border-radius: 3px;

								&::after {
									content: '';
									position: absolute;
									top: 3px;
									left: -8px;
									width: 0;
									height: 0;
									border-width: 8px 12px 6px 0;
									border-style: solid;
									border-color: transparent #fff transparent transparent;
								}
							}
						}
					}
				}

				.self {
					.chat-msg {
						flex-direction: row-reverse;

						.avatar {
							-webkit-text-fill-color: #fa745f;
						}

						.msg-content {
							padding: 0 12px 0 42px;

							.name-box {
								text-align: right;
								padding: 0 2px 0 0;
							}

							.msg-box {
								float: right;
								background-color: #d9feda;

								&::after {
									left: unset;
									right: -8px;
									border-width: 8px 0 6px 12px;
									border-color: transparent transparent transparent #d9feda;
								}
							}
						}
					}
				}
			}
		}

		.send-input {
			width: 100%;
			display: flex;
			align-items: center;
			padding-left: 6px;
			background-color: #fff;
			box-sizing: border-box;

			.uni-searchbar {
				flex: 1;
			}
		}

		.uni-grid-wrap {
			flex: inherit;
		}

		.grid-item-box {
			flex: 1;
			// position: relative;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 15px 0;

			.uni-icons:before {
				// border: 1px solid;
				border-radius: 20%;
				padding: 10px;
				background-color: #fff;
			}
		}

		.grid-item-box-row {
			flex: 1;
			// position: relative;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			align-items: center;
			justify-content: center;
			padding: 15px 0;
		}
	}
</style>
